let util = require('../common/utils/util.js');
// let config = JSON.stringify(wx.getExtConfigSync()) !== '{}' ? wx.getExtConfigSync() : require('../config.js');
let { config } = require('../common/utils/ws/ws-config.js');
const internal = require('./utils/international.js');
module.exports = {
  onLaunch: function (ops) {
    let scene = ops.scene || 0;
    scene && (this.ws_micro_shop_globalData.scene = scene);
    console.info('-------onLaunch---------', scene);
  },
  onShow: function (ops) {
    let scene = ops.scene || 0;
    scene && (this.ws_micro_shop_globalData.onshowscene = scene);
    console.info('-------onShow---------', scene);
  },
  ws_micro_shop_globalData: {
    shopid: 0,
    isSingle: config.spec_type === '1',
    isMulti: config.spec_type === '2',
    isBrand: config.spec_type === '3',
    loginNum: 0,
    template_type: config.template_type,
    version_type: config.spec_type,
    isSaas: config.module_type !== 'saas',
  },
  imgUrl: config.domain + 'addons/ws_micro_shop/core/web/statics/images/appicon/',
  v8_card_seller_actions_log: [],
  is_on_launch: true,
  // 单商户
  api: require('./utils/api.js'),
  getStoreData: function (logObj = {}) {
    let page = this;
    return new Promise((resolve, reject) => {
      page.ws_micro_shoprequest({
        url: page.api.default.store,
        data: {
          latitude: logObj.latitude ? logObj.latitude : '',
          longitude: logObj.longitude ? logObj.longitude : '',
          visit_platform: logObj.visit_platform === 1 ? 1 : 0,
        },
        success: function (res) {
          if (Number(res.code) === 0) {
            wx.setStorageSync('store', res.data.store);
            wx.setStorageSync('show_customer_service', res.data.show_customer_service);
            wx.setStorageSync('contact_tel', res.data.contact_tel);
            wx.setStorageSync('share_setting', res.data.share_setting);
            resolve(res.data);
          }
        },
        complete: function () {
          // TODO
        },
      });

    });
  },
  getCatList: function () {
    this.ws_micro_shoprequest({
      url: this.api.default.cat_list,
      success: function (res) {
        if (Number(res.code) === 0) {
          let cat_list = res.data.list || [];
          wx.setStorageSync('cat_list', cat_list);
        }
      },
    });
  },

  // 企业微信
  qyCheckSession: function (options) {
    let that = this;
    wx.getSystemInfo({
      success(result) {
        console.log('=====environment=====', result);
        if (result.environment === 'wxwork') {
          wx.qy.checkSession({
            success(res) {
              console.log('checkSession========', res);
              that.ws_micro_shoprequest({
                url: that.api.workwechat.checksession,
                cachetime: 0,
                showLoading: false,
                success(session) {
                  console.log('that.api.workwechat.checksession===', session.data.check);
                  if (!session.data.check) {
                    return that.qyLogin(options);
                  }
                  options.success && options.success();
                },
                fail() {
                  console.log('企业微信验证auth/workwechat/checkSession失败');
                  that.qyLogin(options);
                },
              });
            },
            fail() {
              console.log('企业微信验证checkSession失败');
              that.qyLogin(options);
            },
          });
        }
      },
    });
  },
  // 企业微信登录
  qyLogin: function (options) {
    let that = this;
    wx.qy.login({
      success(result) {
        if (result.code) {
          // 发起网络请求
          console.log('企业微信login,code', result.code);
          that.ws_micro_shoprequest({
            url: that.api.workwechat.userid,
            data: {
              code: result.code,
            },
            cachetime: 0,
            showLoading: false,
            success(res) {
              console.log('that.api.workwechat.userid', res.data);
              wx.setStorageSync('corpid', res.data.corpid);
              wx.setStorageSync('cor_userid', res.data.userid);
              wx.setStorageSync('cor_uniacid', res.data.bindacid);
              wx.setStorageSync('appid', res.data.appid);
              options && options.success && options.success();
            },
            fail(error) {
              console.log('-------login error-------', error);
            }
          });
        } else {
          that.qyCheckSession(options);
          console.log('企业微信login失败！', result);
          options && options.fail && options.fail();
        }
      },
    });
  },

  // TODO，非真正登录方法。
  ws_micro_shoplogin: function (type = '') {
    return new Promise((resolve, reject) => {
      let that = this;
      console.log('ws_micro_shoplogin => wx.login');
      let access_token = wx.getStorageSync('access_token');
      if (type) {
        that.getlogincode(resolve);
      } else {
        if (access_token) {
          let data = {};
          that.shoplogin(data, resolve);
        } else {
          that.getlogincode(resolve);
        }
      }
    });
  },

  getlogincode(resolve) {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          let code = res.code;
          const systemInfo = wx.getSystemInfoSync();
          let data = {
            code: code,
            brand: systemInfo.brand,
            model: systemInfo.model,
          };
          that.shoplogin(data, resolve);
        }
      },
    });
  },

  shoplogin(data, resolve) {
    let that = this;
    that.ws_micro_shop_globalData.scene && (data.scene = this.ws_micro_shop_globalData.scene);

    let pages = getCurrentPages();
    let page = pages[(pages.length - 1)];
    that.ws_micro_shoprequest({
      url: that.api.passport.login2,
      method: 'post',
      data,
      success: function (res) {
        if (Number(res.code) === 0) {
          console.log('micro shop login2 success:', res.data);
          let userInfo = wx.getStorageSync('userInfo');
          userInfo = userInfo || {};
          userInfo.sessionid = res.data.access_token;
          userInfo.openid = res.data.openid;
          wx.setStorageSync('access_token', res.data.access_token);
          wx.setStorageSync('OPENID', res.data.openid);
          wx.setStorageSync('userInfo', userInfo);

          wx.setStorageSync('user_info', {
            nickname: res.data.nickname,
            avatar_url: res.data.avatar_url,
            info: res.data.info,
            is_distributor: res.data.is_distributor,
            parent: res.data.parent,
            id: res.data.id,
            level: res.data.level,
            is_clerk: res.data.is_clerk,
            auth_mode: res.data.auth_mode,
            mobile: res.data.mobile,
          });

          if (!page) {
            return;
          }
          if (that.isWXWork && res.data.isopenqywx && !that.ws_micro_shop_globalData.isSaas){
            that.qyCheckSession({
              success: () => {
                resolve();
              },
              fail: err => {
                console.log('企业微信登录失败', err);
              },
            });
          } else {
            if (that.isWXWork && res.data.isopenqywx) {
              that.qyCheckSession();
            }
            
            resolve();
          }
        } else if (Number(res.code) === 4001) {
          wx.removeStorageSync('access_token');
          that.getlogincode(resolve);
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },

  ws_micro_shoprequest: function (object) {
    let that = this;
    if (!object.data) { object.data = {} }
    if (!object.data.shop_id && object.data.shop_id !== 0) {
      object.data.shop_id = that.ws_micro_shop_globalData.shopid;
    }
    // TODO，remove siteinfo while its not correct under some lifecycle.
    let data = {};
    data._uniacid = (this.siteInfo && this.siteInfo.uniacid) || config.uniacid;
    data._acid = (this.siteInfo && this.siteInfo.acid) || config.acid;
    data.token = (this.siteInfo && this.siteInfo.token) || config.token;
    data.divisionid = (this.siteInfo && this.siteInfo.divisionid) || config.divisionid;
    data.v = (this.siteInfo && this.siteInfo.version) || config.version;
    data.env = this.isWXWork ? 'wxwork' : 'wxapp';
    
    object.cachetime = Number(object.cachetime) || 0;
    let cachekey;
    let timestamp;

    let app = getApp();
    if (object.cachetime) {
      let sign = this.getSign(object.url, object.data);
      cachekey = app.modules + sign;
      timestamp = Date.parse(new Date());
      let cachedata = wx.getStorageSync(cachekey);

      if (cachedata.data && cachedata.expire > timestamp) {
        object.success && object.success(cachedata.data);
        object.complete && object.complete(cachedata);
        return true;
      } else {
        wx.removeStorageSync(cachekey);
      }
    }

    let access_token = wx.getStorageSync('access_token');
    if (access_token) {
      data.access_token = access_token;
    }
    object.data = Object.assign(object.data, data);
    if (!object.oldurl) object.oldurl = object.url;
    object.url = this.concatUrl(object.url, data);

    wx.request({
      url: object.url,
      header: object.header || {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: object.data || {},
      method: object.method || 'GET',
      dataType: object.dataType || 'json',
      success: function (res) {
        if (Number(res.data.code) === -1 || Number(res.data.code) === -109) {
          that.ws_micro_shoplogin(1).then(res => {
            object.url = object.oldurl;
            object.access_token = wx.getStorageSync('access_token');
            that.ws_micro_shoprequest(object);
          });
        } else if (Number(res.data.code) === -2) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          });
        } else if (Number(res.data.code) === -104 || Number(res.data.code) === -105 || Number(res.data.code) === -106) {
          wx.redirectTo({
            url: '/ws_micro_shop_guide/pages/saas/404?msg=' + res.data.msg,
          });
        } else {
          if (object.success) {
            if (object.cachetime) {
              let cachedata = { ...res, expire: timestamp + object.cachetime * 1000 };
              wx.setStorageSync(cachekey, cachedata);
            }
            object.success(res.data); 
          }
        }
      },

      fail: function (res) {
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
          duration: 1500,
        });
        if (object.fail) { object.fail(res) }
      },
      complete: function (res) {
        if (object.complete) { object.complete(res) }
      },
    });
  },
  /**
   * 获取签名。将连接地址的所有的参数按照字母排序后拼接+token进行md5
   * @param {*} url 链接地址
   * @param {*} data 参数{参数名1：值1， 参数名2：值2}
   * @param {*} token 签名token非必填
   */

  concatUrl(url, data) {
      let _ = require('../common/utils/underscore.js');
      let theRequest = [];
      if (data) {
        for (let param in data) {
          if (param && data[param]) {
            theRequest = theRequest.concat({
              name: param,
              value: data[param],
            });
          }
        }
      }
      // 去重
      theRequest = _.uniq(theRequest, true, 'name');
      let urlData = '';
      for (let i = 0; i < theRequest.length; i++) {
        if (theRequest[i] && theRequest[i].name && theRequest[i].value && theRequest[i].value !== '0') {
          urlData += theRequest[i].name + '=' + theRequest[i].value;
          if (i < theRequest.length - 1) {
            urlData += '&';
          }
        }
      }
      return url + '&' + urlData;
    },

  /**
   * 获取签名。将连接地址的所有的参数按照字母排序后拼接+token进行md5
   * @param {*} url 链接地址
   * @param {*} data 参数{参数名1：值1， 参数名2：值2}
   * @param {*} token 签名token非必填
   */
  getSign(url, data, token) {
    let _ = require('../common/utils/underscore.js');
    let md5 = require('../common/utils/md5.js');
    let querystring = '';
    let sign = this.getUrlParam(url, 'sign');
    if (sign || (data && data.sign)) {
      return false;
    } else {
      if (url) {
        querystring = this.getQuery(url);
      }
      if (data) {
        let theRequest = [];
        for (let param in data) {
          if (param && data[param]) {
            theRequest = theRequest.concat({
              name: param,
              value: data[param],
            });
          }
        }
        querystring = querystring.concat(theRequest);
      }
      querystring = _.sortBy(querystring, 'name'); // 排序
      querystring = _.uniq(querystring, true, 'name'); // 去重
      let urlData = '';
      for (let i = 0; i < querystring.length; i++) {
        if (querystring[i] && querystring[i].name && querystring[i].value && querystring[i].value !== '0') {
          urlData += querystring[i].name + '=' + querystring[i].value;
          if (i <= querystring.length - 1) {
            urlData += '&';
          }
        }
      }
      token = token ? token : ((getApp() && getApp().siteInfo.token) || config.token);
      sign = md5(urlData + token);
      return sign;
    }
  },

  getQuery(url) {
    let theRequest = [];
    if (url.indexOf('?') != -1) {
      let str = url.split('?')[1];
      let strs = str.split('&');
      for (let i = 0; i < strs.length; i++) {
        if (strs[i].split('=')[0] && unescape(strs[i].split('=')[1])) {
          theRequest[i] = {
            name: strs[i].split('=')[0],
            value: unescape(strs[i].split('=')[1]),
          };
        }
      }
    }
    return theRequest;
  },
  
  /**
   * 获取链接某个参数
   * @param {*} url 获取链接某个参数
   * @param {*} name 链接地址
   */
  getUrlParam(url, name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象
    let r = url.split('?')[1].match(reg); // 匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; // 返回参数值
  },

  loginBindParent: function (object) {
    let that = this;
    let access_token = wx.getStorageSync('access_token');
    let is_share = !object.parent_id || object.parent_id == 'undefined' || object.parent_id == 0;
    if (!access_token) {
      return;
    } else if (is_share) {
      object.parent_id = that.ws_micro_shop_globalData.parent_id || 0;
    }
    object.parent_id = Number(object.parent_id);
    if (that.ws_micro_shop_globalData.isMulti) {
	  that.getStoreData().then(res => {
        that.shopBindParent(object);
      });
    } else {
      that.shopBindParent(object);
    }
  },
  shopBindParent: function (object) {
    let api = this.api;
    if (!object.share_scene) {
      object.share_scene = '';
    }
    let user_info = wx.getStorageSync('user_info');
    let share_setting = wx.getStorageSync('share_setting');
    this.ws_micro_shop_globalData.onshowscene && (object.scene = this.ws_micro_shop_globalData.onshowscene);
    if ((share_setting && share_setting.level > 0)) {
      this.ws_micro_shoprequest({
        url: api.share.bind_parent,
        data: object,
        success: function (res) {
          if (Number(res.code) === 0) {
            user_info.parent = res.data;
            wx.setStorageSync('user_info', user_info);
          }
        },
      });
      // if (parent_id !== 0) {}
    }
  },
  onHide: function () {
    wx.removeStorageSync('cancel');
    // 统计用户打开次数
    // this.countEnterTimes();
  },
  ws_micro_shop_navigate: function (obj) {
    const getUrl = url => {
      let realUrl = '';
      if (url && url.indexOf('?') !== -1) {
        realUrl = url.substring(0, url.indexOf('?'));
      } else {
        realUrl = url;
      }
      return realUrl;
    };
    const parseQueryString = url => {
      let json = {};
      if (url && url.indexOf('?') !== -1) {
        let arr = url.substr(url.indexOf('?') + 1).split('&');
        arr.forEach(item => {
          let tmp = item.split('=');
          json[tmp[0]] = tmp[1];
        });
      } else {
        json = {};
      }
      return json;
    };
    let url = getUrl(obj.url);
    let params;
    if (url === '/ws_micro_shop/pages/web/web') {
      let str = obj.url.substr(obj.url.indexOf('?') + 1);
      params = {
        [str.substring(0, str.indexOf('='))]: str.substr(str.indexOf('=') + 1),
      };
    } else {
      params = parseQueryString(obj.url);
    }
    let close = obj.close ? obj.close : '';
    params.hasOwnProperty('shopid') && (this.ws_micro_shop_globalData.shopid = params.shopid);
    util.navigateTo(url, params, close);
  },
  parseQueryString(url) {
    let reg_url = /^[^\?]+\?([\w\W]+)$/;
    let reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
    let arr_url = reg_url.exec(url);
    let ret = {};
    if (arr_url && arr_url[1]) {
      let str_para = arr_url[1];
      let result;
      while ((result = reg_para.exec(str_para)) != null) {
        ret[result[1]] = result[2];
      }
    }
    return ret;
  },

  wxAppParams(list, str) {
    if (list && list.length > 0) {
      // 内部模块的正则筛选
      let RegExp = /^\/pages/;
      for (let item of list) {
        if (RegExp.test(item[str])) {
          if (item[str].indexOf('/book/') > 0) {
            item[str] = '/ws_micro_shop_book' + item[str];
          } else if (item[str].indexOf('/pt/') > 0) {
            item[str] = '/ws_micro_shop_pt' + item[str];
          } else if (item[str].indexOf('/miaosha/') > 0) {
            item[str] = '/ws_micro_shop_ms' + item[str];
          } else {
            item[str] = '/ws_micro_shop' + item[str];
          }
        }
      }
      for (let i in list) {
        if (list[i].open_type === 'wxapp') {
          list[i].appData = this.parseQueryString(decodeURIComponent(list[i][str]));
        }
      }
    }
  },

  currentPage: null,
  pageOnLoad: function (page) {
    this.currentPage = page;
    if (typeof page.openWxapp === 'undefined') {
      page.openWxapp = this.openWxapp;
    }
    if (typeof page.showToast === 'undefined') {
      page.showToast = this.pageShowToast;
    }
  },
  // 微商城跳转小程序方法，解析链接地址
  openWxapp: function (e) {
    if (!e.currentTarget.dataset.url) { return }
    let url = e.currentTarget.dataset.url;
    url = parseQueryString(url);
    url.path = url.path ? decodeURIComponent(url.path) : '';
    wx.navigateToMiniProgram({
      appId: url.appId,
      path: url.path,
    });

    function parseQueryString(url) {
      let reg_url = /^[^\?]+\?([\w\W]+)$/;
      let reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
      let arr_url = reg_url.exec(url);
      let ret = {};
      if (arr_url && arr_url[1]) {
        let str_para = arr_url[1];
        let result;
        while ((result = reg_para.exec(str_para)) != null) {
          ret[result[1]] = result[2];
        }
      }
      return ret;
    }
  },

  pageShowToast: function (e) {
    let page = this.currentPage;
    let duration = e.duration || 2500;
    let title = e.title || '';
    let complete = e.complete || null;
    if (page._toast_timer) {
      clearTimeout(page._toast_timer);
    }
    page.setData({
      _toast: {
        title: title,
      },
    });
    page._toast_timer = setTimeout(function () {
      let _toast = page.data._toast;
      _toast.hide = true;
      page.setData({
        _toast: _toast,
      });
      if (typeof complete === 'function') {
        complete();
      }
    }, duration);
  },
  /**
   * 分享送优惠券
   * */
  shareSendCoupon: function (page) {
    wx.showLoading({
      mask: true,
    });
    if (!page.hideGetCoupon) {
      page.hideGetCoupon = function (e) {
        let url = e.currentTarget.dataset.url || false;
        page.setData({
          get_coupon_list: null,
        });
        if (url) {
          wx.navigateTo({
            url: url,
          });
        }
      };
    }
    this.ws_micro_shoprequest({
      url: this.api.coupon.share_send,
      success: function (res) {
        if (Number(res.code) === 0) {
          page.setData({
            get_coupon_list: res.data.list,
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },

  // 登录成功后不刷新的页面
  loginNoRefreshPage: [
    'ws_micro_shop/pages/index/index',
    'ws_micro_shop/pages/user/user',
  ],
  onError(msg) {
    console.error(msg);
  },
  collectFormId(e) {
    // let formid = e.detail.formId;
    // let openid = wx.getStorageSync('OPENID');
    // this.util.request({
    //   url: 'pushService/api/formid',
    //   data: {
    //     formid,
    //     openid,
    //   },
    //   method: 'GET',
    //   success: res => {

    //   },
    //   fail: res => {

    //   },
    // });
  },
  loadCurrencyUnit() {
    return new Promise(function(resolve, reject) {
      let { siteroot, uniacid }  = config;
      let currency = {
        unit: '￥',
      };
      wx.request({
        url: siteroot + '?i=' + uniacid + '&from=wxapp&c=wxapp&a=home&do=currency',
        success: function(res) {
          if (res.statusCode === 200 && res.data.errno === 0) {
            currency = res.data.data;
          }
          resolve(currency);
        },
        fail: function(e) {
          reject(e);
        },
        complete: function () {

        },
      });
    });
  },
  loadShopSetting() {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ws_micro_shoprequest({
        url: that.api.default.shopSetting,
        success: function (res) {
          if (Number(res.code) === 0) {
            resolve(res.data);
          }
        },
        fail: function (e) {
          reject(e);
        },
      });
    });
  },
  isSinglePage(page, len) {
    let tabbar = (config.appJson).filter(function (item) {
      return item.tabBar.list.length > 0;
    });
    let count = false;
    for (let i in tabbar) {
      if (Object.prototype.hasOwnProperty.call(tabbar, i)) {
        let item = tabbar[i].tabBar.list;
        for (let j in item) {
          if (item[j].pagePath !== page && Number(len) === 1) {
            count = true;
          }
        }
      }
    }
    return count;
  },
  bindGuide(object) {
    if (object.guide_id) {
      this.ws_micro_shoprequest({
        url: this.api.staff.bind_client,
        data: { staff_id: object.guide_id, shop_id: object.shopid },
        success: function (res) {
          if (Number(res.code) === 0) {
            console.info(res);
          }
        },
      });
    }
  },
  getCoupon(options, page) {
    this.ws_micro_shoprequest({
      url: this.api.default.guide_coupon,
      data: {
        guide_id: options.guide_id,
        coupon_id: options.id,
      },
      success: function(res) {
        if (res.code === 0) {
          page.setData({
            guideCouponPrice: res.data.sub_price,
            isGuideCoupon: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  getGuideCoupon(id, page) {
    this.ws_micro_shoprequest({
      url: this.api.coupon.receive,
      data: {
        id,
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: '领取成功，已放入个人中心-我的优惠券',
            icon: 'none',
            duration: 2000
          });
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: function () {
        page.setData({
          isGuideCoupon: false,
        });
      }
    });
  },
  bindCard(from_openid, share_scene) { // 绑定名片上下级关系 通过分享
    let openid = wx.getStorageSync('OPENID');
    if (!from_openid || !openid) {
      return;
    }
    util.request({
      url: 'card/record/bindRelationThoughCard',
      data: {
        openid,
        from_openid,
        source: 1,
        share_scene,
      },
      success: res => {
        console.log(res);
      },
    });
  },
  bindCard2(opt = {}) { // 绑定名片上下级关系  首页主动调起
    let openid = wx.getStorageSync('OPENID');
    util.request({
      url: 'card/record/bindRelationThoughCard',
      data: {
        openid,
        uid: opt.uid ? opt.uid : '',
        share_scene: 1,
      },
      success: res => {
      
      },
    });
  },
  getPayTypeList(pay_type_list, offline, orderInfo = [], isMulti) {
    let pay_list = [];
    for (let i in pay_type_list) {
      if (Object.prototype.hasOwnProperty.call(pay_type_list, i)) {
        let item = pay_type_list[i];
        if (!isMulti || (isMulti && orderInfo.length === 1)) {
          if (((offline === 1 && item.payment != 2) || (offline === 1 && item.payment === 6)) || (offline === 0 && item.payment != 6) || (offline === 3 && item.payment != 6)) pay_list.push(item);
        } else if (isMulti && orderInfo.length > 1) {
          if (item.payment == 0 || item.payment == 5 || item.payment == 3) pay_list.push(item);
        }
      }
    }
    return pay_list;
  },
  getpayment(list, num) {
    let index = 0;
    if (list) {
      for (let i in list) {
        if (Object.prototype.hasOwnProperty.call(list, i)) {
          let item = list[i];
          if (Number(item.payment) === Number(num)) return i;
        }
      }
    }
    return index;
  },
  getTabBarStatus() {
    // 判断当前页面在不在虚拟菜单中
    let tabBarPages =
      (this.siteInfo &&
        this.siteInfo.appJson[0] &&
        this.siteInfo.appJson[0].tabBar &&
        this.siteInfo.appJson[0].tabBar.v_list) || [];
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1].route;

    let f = tabBarPages.some(function (v) {
      return v.pagePath.indexOf(currentPage) > -1;
    });
    return f;
    
  },

  getUrlStatus(url) {
    // 判断当前页面在不在菜单中
    url.indexOf('?') !== -1 && (url = url.split('?')[0]);
    let tabBarPages =
      (this.siteInfo &&
        this.siteInfo.appJson[0] &&
        this.siteInfo.appJson[0].tabBar &&
        this.siteInfo.appJson[0].tabBar.list) || [];

    let f = tabBarPages.some(function (v) {
      return v.pagePath.indexOf(url) > -1;
    });
    return f;
    
  },

  /**
   * 重置购物车物品个数
   * @param {*} num 传-1表示删除设置
   */
  resetPurchasedNum(num = 0) {
    const targetPath = 'ws_micro_shop/pages/cart/cart'; // 购物车页路径
    let that = this;
    let tabBarPages =
      (that.siteInfo &&
        that.siteInfo.appJson[0] &&
        that.siteInfo.appJson[0].tabBar &&
        that.siteInfo.appJson[0].tabBar.list) || [];
    let index = tabBarPages.findIndex(item => item.pagePath === targetPath);
    if (Number(num) === -1 && index >= 0) { // num为-1时删除菜单badge标识
      wx.removeTabBarBadge({
        index: index,
      });
      return;
    }
    index >= 0 && that.ws_micro_shoprequest({
      url: that.api.cart.get_cart_num,
      method: 'GET',
      success: function(res) {
        let { count } = res.data;
        count && wx.setTabBarBadge({
          index: index,
          text: String(count),
        });
      },
    });
  },

  /**
   * 获取订阅消息tmplids
   * @param {*} type
   * --- 0 : 普通商品／秒杀商品 支付成功通知、发货通知
   * --- 1 ：普通商品／秒杀商品 取消订单通知
   * --- 2 ：普通商品／秒杀商品 退款通知
   * --- 3 ：拼团商品 拼团成功通知、拼团失败通知
   * --- 4 ：预约商品 预约成功通知、预约失败通知
   */
  getSubscribeTmplIds(type) {
    return new Promise(function (resolve, reject) {
      util.request({
        url: 'auth/subscribe/getTmplIds',
        data: { type },
        method: 'GET',
        success: function(res) {
          console.log('获取订阅消息tmplIds返回成功：', res);
          resolve(res); 
        },
        fail: function(res) {
          console.log('获取订阅消息tmplIds返回失败：', res);
          resolve(res);
        },
      });
    });
  },

  getSubscribeMessage( type) {
    let that = this;
    return new Promise((resolve, reject) =>{
      that.getSubscribeTmplIds(type).then(res =>{
        let  {tmplids} = res.data.message;
        tmplids.length > 0 ? wx.requestSubscribeMessage({
          tmplIds: tmplids,
          success: res => {resolve()},
          fail: res => {resolve()}
        }) : resolve();
      })
    })
  },
  getSystemInfo() {//获取导航栏高度
    var app = getApp();
    if (app.globalSystemInfo && !app.globalSystemInfo.ios) {
      return app.globalSystemInfo;
    } else {
      let systemInfo = wx.getSystemInfoSync();
      let ios = !!(systemInfo.system.toLowerCase().search('ios') + 1);
      let rect;
      try {
        rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null;
        if (rect === null) {
          throw 'getMenuButtonBoundingClientRect error';
        }
        //取值为0的情况  有可能width不为0 top为0的情况
        if (!rect.width || !rect.top || !rect.left || !rect.height) {
          throw 'getMenuButtonBoundingClientRect error';
        }
      } catch (error) {
        let gap = ''; //胶囊按钮上下间距 使导航内容居中
        let width = 96; //胶囊的宽度
        if (systemInfo.platform === 'android') {
          gap = 8;
          width = 96;
        } else if (systemInfo.platform === 'devtools') {
          if (ios) {
            gap = 5.5; //开发工具中ios手机
          } else {
            gap = 7.5; //开发工具中android和其他手机
          }
        } else {
          gap = 4;
          width = 88;
        }
        if (!systemInfo.statusBarHeight) {
          //开启wifi的情况下修复statusBarHeight值获取不到
          systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20;
        }
        rect = {
          //获取不到胶囊信息就自定义重置一个
          bottom: systemInfo.statusBarHeight + gap + 32,
          height: 32,
          left: systemInfo.windowWidth - width - 10,
          right: systemInfo.windowWidth - 10,
          top: systemInfo.statusBarHeight + gap,
          width: width
        };
        console.log('error', error);
        console.log('rect', rect);
      }

      let navBarHeight = '';
      if (!systemInfo.statusBarHeight) {
        systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20;
        navBarHeight = (function() {
          let gap = rect.top - systemInfo.statusBarHeight;
          return 2 * gap + rect.height;
        })();

        systemInfo.statusBarHeight = 0;
        systemInfo.navBarExtendHeight = 0; //下方扩展4像素高度 防止下方边距太小
      } else {
        navBarHeight = (function() {
          let gap = rect.top - systemInfo.statusBarHeight;
          return systemInfo.statusBarHeight + 2 * gap + rect.height;
        })();
        if (ios) {
          systemInfo.navBarExtendHeight = 4; //下方扩展4像素高度 防止下方边距太小
        } else {
          systemInfo.navBarExtendHeight = 0;
        }
      }
      systemInfo.navBarHeight = navBarHeight; //导航栏高度不包括statusBarHeight
      systemInfo.capsulePosition = rect; //右上角胶囊按钮信息bottom: 58 height: 32 left: 317 right: 404 top: 26 width: 87 目前发现在大多机型都是固定值 为防止不一样所以会使用动态值来计算nav元素大小
      systemInfo.ios = ios; //是否ios

      app.globalSystemInfo = systemInfo; //将信息保存到全局变量中,后边再用就不用重新异步获取了

      //console.log('systemInfo', systemInfo);
      return systemInfo;
    }
  },
  handleStatisticsShare(options) {
    let that = this;
    // 统计分享
    return new Promise((resolve, reject) => {
      const { type = '', param_id = '' } = options;
      app.ws_micro_shoprequest({
        url: that.api.staff.share_submit,
        data: {
          type,
          param_id,
        },
        method: 'post',
        success: res => {
          if (res && res.code === 0) {
            resolve(true);
          } else {
            reject(false);
          }
        },
        fail: res => {
          reject(false);
        },
      });
    });
  },
  getSetting() {
  	let that = this;
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
            wx.getLocation({
              success: function(res) {
                wx.setStorageSync('userLocation', res);
                resolve(res);
              },
              fail: function() {
                resolve({});
              },
            });
          } else if (res.authSetting['scope.userLocation'] === false) {
            that.setData({
              open_setting: true,
            });
            resolve({});
          } else {
            wx.getLocation({
              success: function(res) {
                wx.setStorageSync('userLocation', res);
                resolve(res);
              },
              fail: function() {
                resolve({});
              },
            });
          }
        },
      });
    });
  },
};
